import echarts from 'echarts';
import React from 'react';
import elementResizeEvent from 'element-resize-event';

require('echarts/lib/chart/line');
require('echarts/lib/chart/lines');
require('echarts/lib/chart/bar');
require('echarts/lib/chart/pie');
require('echarts/lib/component/gridSimple');
require('echarts/lib/component/legend');
require('echarts/lib/chart/funnel');

class ReactEcharts extends React.Component {
  static propTypes = {
    option: React.PropTypes.object.isRequired,
    notMerge: React.PropTypes.bool,
    lazyUpdate: React.PropTypes.bool,
    style: React.PropTypes.object,
    className: React.PropTypes.string,
    theme: React.PropTypes.string,
    onChartReady: React.PropTypes.func,
    showLoading: React.PropTypes.bool,
    onEvents: React.PropTypes.object,
  };
  // first add
  componentDidMount() {
    const echartObj = this.renderEchartDom();
    const onEvents = this.props.onEvents || {};

    this.bindEvents(echartObj, onEvents);
    // on chart ready
    if (typeof this.props.onChartReady === 'function') this.props.onChartReady(echartObj);

    // on resize
    elementResizeEvent(this.echartsDom, () => {
      echartObj.resize();
    });
  }

  // update
  componentDidUpdate() {
    this.renderEchartDom();
    this.bindEvents(this.getEchartsInstance(), this.props.onEvents || []);
  }

  // remove
  componentWillUnmount() {
    echarts.dispose(this.echartsDom);
  }

  getEchartsInstance() {
    // return the echart object
    return echarts.getInstanceByDom(this.echartsDom) || echarts.init(this.echartsDom,
        this.props.theme);
  }

  // bind the events
  bindEvents = (instance, events) => {
    const _loop = function _loop(eventName) {
      // ignore the event config which not satisfy
      if (typeof eventName === 'string' && typeof events[eventName] === 'function') {
        // binding event
        instance.off(eventName);
        instance.on(eventName, (param) => {
          events[eventName](param, instance);
        });
      }
    };

    for (const eventName in events) {
      _loop(eventName);
    }
  };

  // render the dom
  renderEchartDom() {
    // init the echart object
    const echartObj = this.getEchartsInstance();
    // set the echart option
    echartObj.setOption(this.props.option,
      this.props.notMerge || false, this.props.lazyUpdate || false);
    // set loading mask
    if (this.props.showLoading) echartObj.showLoading();
    else echartObj.hideLoading();

    return echartObj;
  }


  render() {
    const style = this.props.style || {
      height: '300px',
    };
    // for render
    return (
      <div
        ref={(echartsDom) => { this.echartsDom = echartsDom; }}
        className={this.props.className}
        style={style}
      />
    );
  }
}

module.exports = ReactEcharts;
